<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<uni-icons type="back" size="28" color="#fff" @click="goBack" />
			<text class="title">就近加油</text>
			<view class="right-icons"></view>
		</view>

		<!-- 搜索框 -->
		<view class="search-bar">
			<input class="search-input" placeholder="输入需要搜索的内容" @input="handleSearch" v-model="searchText" />
			<uni-icons type="search" size="22" color="#999" />
		</view>

		<!-- 油号选择 -->
		<view class="oil-type-list">
			<view v-for="item in oilTypes" :key="item" :class="['oil-type', selectedOil === item ? 'active' : '']"
				@click="selectOil(item)">
				{{ item }}
			</view>
		</view>

		<!-- 列表模式按钮 -->
		<view class="list-mode-btn" @click="toListMode">
			列表模式
		</view>

		<!-- 地图区域 -->
		<view class="map-card">
			<map class="map" 
				:latitude="latitude" 
				:longitude="longitude" 
				:markers="covers"
				@markertap="markerTap"
				:scale="14"
				show-location>
			</map>
		</view>

		<!-- 门店信息卡片 -->
		<view class="station-info-card" v-if="selectedStation">
			<view>
				<view class="station-title">{{ selectedStation.name }}</view>
				<view class="station-address">{{ selectedStation.address }}</view>
				<view class="station-price">{{ selectedOil }}: ¥{{ getSelectedOilPrice(selectedStation.id) }}</view>
				<view class="station-detail">
					<uni-icons type="info" size="20" color="#1976d2" />
					<text class="station-detail-link" @click="toDetails(selectedStation)">门店详情&gt;&gt;</text>
				</view>
			</view>
			<image :src="selectedStation.img" class="station-img" mode="aspectFill" />
			<button class="nav-btn" @click="toNav(selectedStation)">立即导航</button>
		</view>
	</view>
</template>

<script>
	import request from '../../../uitls/request';

	export default {
		data() {
			return {
				id: 0,
				title: 'map',
				latitude: 39.909,
				longitude: 116.39742,
				covers: [],
				oilTypes: [],
				selectedOil: '',
				stations: [],
				allStations: [],
				searchText: '',
				gasTypeMap: {},
				gasTypeList: [],
				selectedStation: null,
				currentLocationMarker: null
			}
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			toListMode() {
				uni.redirectTo({
					url: '/pages/nearby-gas/nearby-gas'
				});
			},
			toNav(station) {
				uni.navigateTo({
					url: '/pages/nearby-gas/navigate/navigate?latitude=' + station.latitude + '&longitude=' + station.logitude
				});
			},
			toDetails(station) {
				uni.navigateTo({
					url: '/pages/shopDetails/shopDetails?id=' + station.id
				})
			},
			selectOil(item) {
				this.selectedOil = item;
			},
			handleSearch(e) {
				this.searchText = e.detail.value;
				this.filterStations();
			},
			filterStations() {
				if (!this.searchText) {
					this.stations = this.allStations;
				} else {
					this.stations = this.allStations.filter(station => 
						station.name.toLowerCase().includes(this.searchText.toLowerCase())
					);
				}
				this.updateMapMarkers();
			},
			updateMapMarkers() {
				let markers = [this.currentLocationMarker];
				
				const stationMarkers = this.stations.map((station, index) => ({
					id: index,
					latitude: station.latitude,
					longitude: station.logitude,
					iconPath: '../../../static/定位.png',
					width: 30,
					height: 30,
					callout: {
						content: station.name,
						color: "white",
						borderRadius: 30,
						bgColor: "orange"
					}
				}));
				
				this.covers = [...markers, ...stationMarkers];

				if (this.selectedStation) {
					const selectedMarker = stationMarkers.find(marker => 
						marker.latitude === this.selectedStation.latitude && 
						marker.longitude === this.selectedStation.logitude
					);
					if (selectedMarker) {
						this.latitude = selectedMarker.latitude;
						this.longitude = selectedMarker.longitude;
					}
				}
			},
			markerTap(e) {
				const station = this.stations[e.markerId];
				this.selectedStation = station;
				this.latitude = station.latitude;
				this.longitude = station.logitude;
			},
			getSelectedOilPrice(stationId) {
				const selectedType = this.gasTypeList.find(type => type.name === this.selectedOil);
				if (selectedType && this.gasTypeMap[stationId]) {
					return this.gasTypeMap[stationId][selectedType.id] || '暂无价格';
				}
				return '暂无价格';
			},
			getCurrentLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						this.currentLocationMarker = {
							id: -1,
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: '../../../static/当前位置.png',
							width: 40,
							height: 40,
							callout: {
								content: "我的位置",
								color: "white",
								borderRadius: 30,
								bgColor: "#2e8bff"
							}
						};
						this.loadStations();
					},
					fail: (err) => {
						console.error('获取位置失败：', err);
					}
				});
			},
			loadStations() {
				request({
					url: '/xsc/cheer/list',
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							this.allStations = res.data.rows.map(station => ({
								...station,
								distance: this.calculateDistance(
									this.latitude,
									this.longitude,
									station.latitude,
									station.logitude
								)
							}));
							this.filterStations();
						}
					}
				});
			},
			loadGasTypeRelations() {
				request({
					url: '/xsc/gas_cheer_type/list',
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							this.gasTypeMap = {};
							res.data.rows.forEach(item => {
								if (!this.gasTypeMap[item.gasCheerId]) {
									this.gasTypeMap[item.gasCheerId] = {};
								}
								this.gasTypeMap[item.gasCheerId][item.gasTypeId] = item.price;
							});
						}
					}
				});
			},
			loadGasTypes() {
				request({
					url: '/xsc/gastype/list',
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							this.gasTypeList = res.data.rows;
							this.oilTypes = res.data.rows.map(type => type.name);
							if (this.oilTypes.length > 0) {
								this.selectedOil = this.oilTypes[0];
							}
						}
					}
				});
			},
			calculateDistance(lat1, lon1, lat2, lon2) {
				const earthRadius = 6371;
				const dLat = this.deg2rad(lat2 - lat1);
				const dLon = this.deg2rad(lon2 - lon1);
				
				const a = 
					Math.sin(dLat/2) * Math.sin(dLat/2) +
					Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
					Math.sin(dLon/2) * Math.sin(dLon/2);
				
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
				const distance = earthRadius * c;
				return Number(distance.toFixed(3));
			},
			deg2rad(deg) {
				return deg * (Math.PI / 180);
			}
		},
		onLoad() {
			this.getCurrentLocation();
			this.loadGasTypes();
			this.loadGasTypeRelations();
		}
	}
</script>

<style scoped>
	.container {
		/* #ifdef MP-WEIXIN */
		margin-top: 70rpx;
		/* #endif */
		background: linear-gradient(180deg, #2e8bff, #3ca7fa);
		min-height: 100vh;
		background-repeat: no-repeat;
		background-size: 100% 35%;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40rpx 24rpx 24rpx 24rpx;
	}

	.title {
		color: #fff;
		font-size: 40rpx;
	}

	.right-icons {
		display: flex;
		width: 28px;
	}

	.search-bar {
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 40rpx;
		margin: 24rpx;
		padding: 0 24rpx;
		height: 86rpx;
		width: 70%;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.search-input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 30rpx;
		background: transparent;
		padding: 0 20rpx;
	}

	.list-mode-btn {
		/* #ifdef MP-WEIXIN */
		margin-top: 80rpx;
		/* #endif */
		position: absolute;
		right: 25rpx;
		top: 125rpx;
		background: linear-gradient(135deg, #ff9800, #ff5722);
		color: #fff;
		width: 40px;
		height: 40px;
		padding: 20px;
		border-radius: 50%;
		padding: 5px;
		font-size: 28rpx;
		font-weight: bold;
		box-shadow: 0 4rpx 16rpx rgba(255, 152, 0, 0.2);
		z-index: 10;
		text-align: center;
	}

	.map-card {
		background: #fff;
		border-radius: 24rpx;
		margin: 24rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.map {
		width: 100%;
		height: 600rpx;
		border-radius: 16rpx;
	}

	.station-info-card {
		background: #fff;
		border-radius: 24rpx;
		margin: 24rpx;
		padding: 28rpx;
		box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.04);
		display: flex;
		flex-direction: column;
		position: relative;
	}

	.station-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.station-address {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}

	.station-detail {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.station-detail-link {
		color: #1976d2;
		margin-left: 8rpx;
		margin-right: 16rpx;
		font-size: 28rpx;
	}

	.station-img {
		width: 260rpx;
		height: 160rpx;
		border-radius: 10rpx;
		object-fit: cover;
		position: absolute;
		top: 28rpx;
		right: 28rpx;
	}

	.nav-btn {
		width: 100%;
		background: linear-gradient(90deg, #2e8bff, #3ca7fa);
		color: #fff;
		font-size: 32rpx;
		border-radius: 40rpx;
		margin-top: 20rpx;
	}

	.oil-type-list {
		display: flex;
		gap: 15rpx;
		margin: 0 24rpx 24rpx 24rpx;
		flex-wrap: nowrap;
		overflow-x: auto;
	}

	.oil-type {
		padding: 6rpx 30rpx;
		border-radius: 20rpx;
		background: transparent;
		color: white;
		font-size: 28rpx;
		border: 2rpx solid white;
	}

	.oil-type.active {
		background: white;
		color: #2e8bff;
	}

	.oil-type-list::-webkit-scrollbar {
		display: none;
	}

	.station-price {
		font-size: 28rpx;
		color: #ff5722;
		margin-bottom: 10rpx;
	}
</style>